package session;

import DAO.CouponDAO;
import DAO.ICouponDAO;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NonUniqueResultException;

import entities.Coupon;
import org.hibernate.HibernateException;
import utils.HibernateUtil;


/**
 *
 * @author alex
 */
public class CouponManager implements ICouponManager {

    private ICouponDAO couponDAO = new CouponDAO();

    /** find coupons by details */
    public Coupon findByCouponDeatils(String details) {
        Coupon coupon = null;
        try {
            HibernateUtil.beginTransaction();
            coupon = couponDAO.findByCouponDeatils(details);
            HibernateUtil.commitTransaction();
        } catch (NonUniqueResultException ex) {
            System.out.println("Handle your error here");
            System.out.println("Query returned more than one results.");
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }
        return coupon;
    }

    /** find all coupons */
    public List<Coupon> findAllCoupons() {

         List<Coupon> allCoupons = new ArrayList<Coupon>();
        try {
            HibernateUtil.beginTransaction();
           allCoupons = couponDAO.findAll(Coupon.class);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }
        return allCoupons;
    }

    /** save new coupon*/
    public  void saveNewCoupon(Coupon coupon) {
        try {
            HibernateUtil.beginTransaction();
            couponDAO.save(coupon);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
            HibernateUtil.rollbackTransaction();
        }
    }

    /** find coupons by id */
    public Coupon findCouponById(BigDecimal id) {
        Coupon coupon = null;
        try {
            HibernateUtil.beginTransaction();
            coupon = couponDAO.findByID(Coupon.class, id);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }

        if(coupon==null)
        {
            System.out.println("There is no such coupon in the db with the id: "+id);
        }
        return coupon;
    }

    /** delete coupon */
    public void deleteCoupon(BigDecimal id) {
        Coupon coupon = findCouponById(id);
        if(coupon==null) return;
        try {
            HibernateUtil.beginTransaction();
            couponDAO.delete(coupon);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
            HibernateUtil.rollbackTransaction();
        }
        System.out.println("the coupon: "+ coupon  +" was successfully deleted from the db");
    }
}
